package com.xianyun.book.command;

import com.alibaba.cola.dto.SingleResponse;
import com.xianyun.book.domain.book.Book;
import com.xianyun.book.domain.gateway.BookGateway;
import com.xianyun.book.domain.gateway.OrderGateway;
import com.xianyun.book.domain.order.SalesOrder;
import com.xianyun.book.dto.BookPurchaseCmd;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author ytt
 */
@Slf4j
@Component
public class BookPurchaseCmdExe {
    @Resource
    private OrderGateway orderGateway;

    @Resource
    private BookGateway bookGateway;

    public SingleResponse<String> execute(@Valid BookPurchaseCmd cmd){
        if (checkBookExistAndStock(cmd.getIsbn())){
            //查询成本过高考虑后续用简单SQL进行替换
            Book book = bookGateway.saveOrQueryBookByIsbn(cmd.getIsbn());
            if (book.countInSellerNumber() >= cmd.getNumber()){
                SalesOrder salesOrder = new SalesOrder();
                BeanUtils.copyProperties(cmd,salesOrder);
                salesOrder.setBuyer(true);
                salesOrder.setIsbn(cmd.getIsbn());
                salesOrder.setUserSecurity(cmd.getUserSecurity());
                salesOrder.setBuyNumber(cmd.getNumber());
                salesOrder.setFinenessType(cmd.getFinenessType());
                //创建买书订单
                String orderId = orderGateway.createBookOrder(salesOrder);
                salesOrder.setBuyId(orderId);
                //更新书籍情况
                bookGateway.refreshBook(salesOrder);
                return SingleResponse.of(orderId);
            }
            else {
                return SingleResponse.buildFailure("BIZ_IN_STOCK_LACK","在售数量不足请确认库存再下单!");
            }
        }
        return SingleResponse.buildFailure("BIZ_BOOK_NOT_FOUND","ISBN码对应的书籍不存在请确认无误再下单！");
    }

    private boolean checkBookExistAndStock(String isbn){
        return null != bookGateway.saveOrQueryBookByIsbn(isbn);
    }


}
